import { login, logout, getUserInfo } from '@/api/miva_user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: null,
  matchInfo: null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_MATCH_INFO: (state, matchInfo) => {
    state.matchInfo = matchInfo
  }
}

const actions = {
  // 登录
  login({ commit }, accountInfo) {
    const { account, password } = accountInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password })
        .then(res => {
          const { data: { token }} = res
          commit('SET_TOKEN', token)
          setToken(token)
          resolve(res)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(res => {
          const { data } = res
          commit('SET_USER_INFO', data)
          resolve(data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  // 退出登录
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      removeToken()
      logout().then(res => {
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 暂存匹配信息
  matchInfo({ commit }, matchInfo) {
    return new Promise((resolve, reject) => {
      commit('SET_MATCH_INFO', matchInfo)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
